﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using System.Windows.Forms;
using System.Threading;
using Microsoft.Xna.Framework.Graphics;

namespace XNAViewer
{
    public class XNAViewerComponent : DrawableGameComponent
    {
        private XNAViewer control;
        private Form formWindow;

        private ManualResetEvent manualResetEvent = new ManualResetEvent(true);

        private GraphicsDevice graphicsDevice;

        public XNAViewerComponent(Game game, XNAViewer control)
            : base(game)
        {
            this.control = control;
            formWindow = (Form)Form.FromHandle(game.Window.Handle);
            formWindow.TopLevel = false;
            this.DrawOrder = int.MaxValue;
        }

        public void PauseGame()
        { manualResetEvent.Reset(); }

        public void ResumeGame()
        { manualResetEvent.Set(); }

        public override void Update(GameTime gameTime)
        {
            manualResetEvent.WaitOne();
            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
            if (!control.Disposing)
            {
                //Detect Change of GraphicsDevice
                if (Game.GraphicsDevice != graphicsDevice)
                {
                    graphicsDevice = GraphicsDevice;
                    control.PerformLayout();
                }
                if (control.Crop)
                    Game.GraphicsDevice.Present(control.CropRectangle, null, control.Handle);
                else
                    Game.GraphicsDevice.Present(null, null, control.Handle);
            }
            base.Draw(gameTime);
        }
    }
}
